package com.dgut.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dgut.dto.ProductsPageDTO;
import com.dgut.entity.Products;
import com.dgut.result.PageResult;
import com.dgut.result.Result;
import com.dgut.service.ProductsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
@Api(tags = "产品管理接口")
@Slf4j
public class ProductsController {
    @Autowired
    private ProductsService productsService;

    /**
     * 分页查询
     *
     * @param productsPageDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("分页查询产品信息")
    public Result pageQuery(ProductsPageDTO productsPageDTO) {
        log.info("分页查询产品信息: 参数productsPageDTO:{}", productsPageDTO);
        Integer currentPage = productsPageDTO.getCurrentPage();
        Integer pageSize = productsPageDTO.getPageSize();
        Page<Products> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(productsPageDTO.getProductName() != null &&
                        productsPageDTO.getProductName().length() > 0,
                "product_name", productsPageDTO.getProductName());
        Page<Products> p = productsService.page(page, queryWrapper);

        return Result.success(new PageResult(p.getTotal(), p.getRecords()));
    }


    /**
     * 新增
     *
     * @param products
     * @return
     */
    @ApiOperation("新增产品")
    @PostMapping
    public Result save(@RequestBody Products products) {
        log.info("新增产品: 参数products:{}", products);
        productsService.save(products);
        return Result.success();
    }

    /**
     * 修改
     *
     * @param products
     * @return
     */
    @ApiOperation("修改产品")
    @PutMapping
    public Result update(@RequestBody Products products) {
        log.info("修改产品: 参数products:{}", products);
        productsService.updateById(products);
        return Result.success();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @ApiOperation("删除产品")
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids) {
        log.info("删除产品: 参数id:{}", ids);
        productsService.removeBatchByIds(ids);
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("查询所有产品")
    public Result list() {
        log.info("查询所有产品");
        List<Products> list = productsService.list();
        return Result.success(list);
    }
}
